<template>
  <div class="product-detail" v-if="product">
    <div class="product-image">
      <img :src="product.image" :alt="product.name">
    </div>
    <div class="product-info">
      <h1>{{ product.name }}</h1>
      <p class="price">¥{{ product.price.toFixed(2) }}</p>
      <p class="description">{{ product.description }}</p>
      <div class="actions">
        <button @click="addToCart" class="add-to-cart-btn">加入购物车</button>
        <button @click="buyNow" class="buy-now-btn">立即购买</button>
      </div>
      <div class="product-details">
        <h2>商品详情</h2>
        <pre>{{ product.details }}</pre>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useProductStore } from '../stores/productStore';
import { useCartStore } from '../stores/cartStore';
const route = useRoute();
const router = useRouter();
const productStore = useProductStore();
const cartStore = useCartStore();
const product = ref(null);
onMounted(() => {
  const productId = parseInt(route.params.id);
  product.value = productStore.getProductById(productId);
  if (!product.value) {
    router.push('/'); // 如果产品不存在，重定向到首页
  }
});
const addToCart = () => {
  cartStore.addToCart(product.value);
  // 移除了 alert('商品已添加到购物车！');
};
const buyNow = () => {
  cartStore.clearCart();
  cartStore.addToCart(product.value);
  router.push('/Order/payment');
};
</script>
<style scoped>
.product-detail {
  display: flex;
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
}
.product-image {
  flex: 1;
  margin-right: 2rem;
  text-align: center;
}
.product-image img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  width: 400px;
  height: 400px;
  object-fit: cover;
}
.product-info {
  flex: 1;
}
h1 {
  font-size: 2rem;
  margin-bottom: 1rem;
}
.price {
  font-size: 1.5rem;
  color: #e44d26;
  margin-bottom: 1rem;
}
.description {
  margin-bottom: 2rem;
}
.actions {
  display: flex;
  gap: 1rem;
}
button {
  flex: 1;
  padding: 0.75rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 1rem;
}
.add-to-cart-btn {
  background-color: #4caf50;
  color: white;
}
.buy-now-btn {
  background-color: #f44336;
  color: white;
}
button:hover {
  opacity: 0.9;
}
.product-details {
  margin-top: 2rem;
  border-top: 1px solid #eee;
  padding-top: 1rem;
}
.product-details h2 {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
.product-details pre {
  white-space: pre-wrap;
  font-family: inherit;
  line-height: 1.6;
}
@media (max-width: 768px) {
  .product-detail {
    flex-direction: column;
  }
  .product-image {
    margin-right: 0;
    margin-bottom: 2rem;
  }
}
</style>
